package sd_services

import (
	"fmt"
	"log"
	"strings"
	"time"
	"xiehui-service/app/models/erp_models"
	"xiehui-service/app/models/sd_models"
	"xiehui-service/global"
	"xiehui-service/utils"

	"go.uber.org/zap"
)

type taskService struct {
}

type Pagination struct {
	PageNum  int
	PageSize int
}

var TaskService = new(taskService)

// 查询订单
func (taskService *taskService) TaskList(stamp float64, num int64) (task []sd_models.Task, err error) {
	err = global.App.MSACCESS.Ping()
	if err != nil {
		log.Println("ping==>>", err)
		global.App.Log.Error("查询订单数据失败：", zap.Any("数据库联接", "ping失败"))
		return nil, err
	}

	TaskColNames := sd_models.Task{}.GenerateColumnNames()
	TaskColsStr := strings.Join(TaskColNames, ", ")
	rows, err := global.App.MSACCESS.Query(fmt.Sprintf("SELECT Top %d %s FROM Task WHERE Stamp > %.10f order by DatTim asc", num, TaskColsStr, stamp))

	if err != nil {
		log.Println("query==>>", err)
		global.App.Log.Error("查询订单数据失败：", zap.Any("Query查询失败", err))
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var taskItem sd_models.Task

		var scanFields = []interface{}{
			&taskItem.ID,
			&taskItem.Code,
			&taskItem.DatTim,
			&taskItem.Attribute,
			&taskItem.Contract,
			&taskItem.Customer,
			&taskItem.ProjName,
			&taskItem.ProjType,
			&taskItem.ProjGrade,
			&taskItem.ProjArea,
			&taskItem.ProjAdr,
			&taskItem.Distance,
			&taskItem.ConsPos,
			&taskItem.Pour,
			&taskItem.Variety,
			&taskItem.BetLev,
			&taskItem.Filter,
			&taskItem.Freeze,
			&taskItem.Lands,
			&taskItem.Cement,
			&taskItem.Stone,
			&taskItem.BnSize,
			&taskItem.AddLiq,
			&taskItem.Request,
			&taskItem.Recipe,
			&taskItem.MixLast,
			&taskItem.MorRec,
			&taskItem.Mete,
			&taskItem.BegTim,
			&taskItem.EndTim,
			&taskItem.Attamper,
			&taskItem.Data,
			&taskItem.Flag,
			&taskItem.Notes,
			&taskItem.TotVehs,
			&taskItem.TotMete,
			&taskItem.Stamp,
			&taskItem.Contacts,
			&taskItem.ContTel,
			&taskItem.Bend,
		}
		if err := rows.Scan(scanFields); err != nil {
			log.Println("scan==>>", err)
		}
		task = append(task, taskItem)
	}

	if err := rows.Err(); err != nil {
		log.Println("rows.err==>>", err)
		global.App.Log.Error("查询订单数据失败：", zap.Any("查询失败", err))
		return nil, err
	}

	return task, nil
}

// 新增数据
func (taskService *taskService) Create(task sd_models.Task) (taskId string, err error) {
	TaskColNames := task.GenerateColumnNames()
	TaskColsStr := strings.Join(TaskColNames, ", ")
	ValuesPlaceholder := strings.Repeat("?, ", len(TaskColNames)-1) + "?"

	// 构建 Insert SQL 语句
	query := fmt.Sprintf("INSERT INTO Task (%s) VALUES (%s)", TaskColsStr, ValuesPlaceholder)

	stmt, err := global.App.MSACCESS.Prepare(query)
	if err != nil {
		return
	}
	defer stmt.Close()
	var execFields = []interface{}{
		task.ID,
		task.Code,
		task.DatTim,
		task.Attribute,
		task.Contract,
		task.Customer,
		task.ProjName,
		task.ProjType,
		task.ProjGrade,
		task.ProjArea,
		task.ProjAdr,
		task.Distance,
		task.ConsPos,
		task.Pour,
		task.Variety,
		task.BetLev,
		task.Filter,
		task.Freeze,
		task.Lands,
		task.Cement,
		task.Stone,
		task.BnSize,
		task.AddLiq,
		task.Request,
		task.Recipe,
		task.MixLast,
		task.MorRec,
		task.Mete,
		task.BegTim,
		task.EndTim,
		task.Attamper,
		task.Data,
		task.Flag,
		task.Notes,
		task.TotVehs,
		task.TotMete,
		task.Stamp,
		task.Contacts,
		task.ContTel,
		task.Bend,
	}

	_, err = stmt.Exec(execFields...)
	if err != nil {
		return
	}

	return task.ID, err
}

// 根据ID查询数据
func (taskService *taskService) GetTaskByID(id string) (*sd_models.Task, error) {
	err := global.App.MSACCESS.Ping()
	if err != nil {
		log.Println("ping==>>", err)
		global.App.Log.Error("[Task]查询数据失败：", zap.Any("数据库联接", "ping失败"))
		return nil, err
	}

	TaskColNames := sd_models.Task{}.GenerateColumnNames()
	TaskColsStr := strings.Join(TaskColNames, ", ")
	sql := fmt.Sprintf("SELECT Top 1 %s FROM Task WHERE ID = ?", TaskColsStr)

	row := global.App.MSACCESS.QueryRow(sql, id)
	var task sd_models.Task
	var scanFields = []interface{}{
		&task.ID,
		&task.Code,
		&task.DatTim,
		&task.Attribute,
		&task.Contract,
		&task.Customer,
		&task.ProjName,
		&task.ProjType,
		&task.ProjGrade,
		&task.ProjArea,
		&task.ProjAdr,
		&task.Distance,
		&task.ConsPos,
		&task.Pour,
		&task.Variety,
		&task.BetLev,
		&task.Filter,
		&task.Freeze,
		&task.Lands,
		&task.Cement,
		&task.Stone,
		&task.BnSize,
		&task.AddLiq,
		&task.Request,
		&task.Recipe,
		&task.MixLast,
		&task.MorRec,
		&task.Mete,
		&task.BegTim,
		&task.EndTim,
		&task.Attamper,
		&task.Data,
		&task.Flag,
		&task.Notes,
		&task.TotVehs,
		&task.TotMete,
		&task.Stamp,
		&task.Contacts,
		&task.ContTel,
		&task.Bend,
	}
	if err = row.Scan(scanFields...); err != nil {
		log.Println("GetTaskByID scan==>>", err)
		global.App.Log.Error("[Task]查询数据失败：", zap.Any("原因", err))
		return nil, err
	}

	return &task, nil
}

// 更新数据
func (taskService *taskService) Update(erpTask erp_models.OrderTask) (taskId int64, err error) {
	query := `UPDATE Task SET
		Customer = ?,
		ProjName = ?,
		ConsPos = ?,
		Mete = ?,
		MixLast = ?,
		Stamp = ? 
		WHERE ID = ? `
	stmt, err := global.App.MSACCESS.Prepare(query)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(erpTask.CustomerName, erpTask.ProjectName, erpTask.BuildPosition, erpTask.PlanQuantity, erpTask.MixingTime, utils.DateTimeToStamp(erpTask.UpdatedAt.Format(time.DateTime)), erpTask.ID.ID)
	if err != nil {
		return
	}

	return int64(erpTask.ID.ID), err
}

func (taskService *taskService) UpdateFlag(flag string, code string) (err error) {
	query := `UPDATE Task SET
		Flag = ?
		WHERE Code = ? `
	stmt, err := global.App.MSACCESS.Prepare(query)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(flag, code)
	if err != nil {
		return
	}

	return err
}
